package com.game.server.util;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GetBeanFromResultUtil {

    private GetBeanFromResultUtil() {
    }

    public static <T> List<T> getBeans(ResultSet resultSet, Class<T> className) {
        List<T> list = new ArrayList<T>();
        Field fields[] = className.getDeclaredFields();
        try {
            while (resultSet.next()) {
                T instance = className.newInstance();
                for (Field field : fields) {
                    Object result = resultSet.getObject(field.getName());
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    field.set(instance, result);
                    field.setAccessible(flag);
                }
                list.add(instance);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     *
     * @param resultSet
     * @param className
     * @param aliasMap  别名map  key 别名  value 原名
     * @param <T>
     * @return
     */
    public static <T> T getBean(ResultSet resultSet, Class<T> className, Map<String,String>  aliasMap) {
        T instance = null;
        try {
            instance = className.newInstance();
            Field fields[] = className.getFields();
            for (Field field : fields) {
                String name = field.getName();
                if (aliasMap!=null && aliasMap.size()>0){
                    name = aliasMap.get(field.getName());
                    if (name==null){
                        name = field.getName();
                    }
                }
                try {
                    Object result = resultSet.getObject(name);
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    field.set(instance, result);
                    field.setAccessible(flag);
                }catch (SQLException e){

                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }
}
